package com.lonwin.mes2u8.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lonwin.mes2u8.common.MesConfig;
import com.lonwin.mes2u8.common.YonYouConfig;
import com.lonwin.mes2u8.domain.mes.MesCommonResult;
import com.lonwin.mes2u8.domain.mes.MesSaleOrderInfo;
import com.lonwin.mes2u8.domain.u8.U8CommonSyncResponse;
import com.lonwin.mes2u8.domain.u8.U8SaleOrderAddParam;
import com.lonwin.mes2u8.domain.u8.U8SaleOrderQueryParam;
import com.lonwin.mes2u8.domain.u8.U8SaleOrderQueryResult;
import com.lonwin.mes2u8.util.MyHttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import openapi4j.exception.OpenAPIException;
import openapi4j.service.SaleOrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 销售订单相关方法
 *
 * @author DELL
 * @Date 2023-12-16 9:43
 */
@Service
@Slf4j
public class SaleOrderAppService {
    @Resource
    private YonYouConfig yonYouConfig;
    @Resource
    private MesConfig mesConfig;
    @Resource
    private MesTokenService mesTokenService;

    /**
     * 根据销售订单编号查询销售订单详情
     *
     * @param batchCode 销售订单编号
     * @return 销售订单详情
     */
    public List<MesSaleOrderInfo> getMesSaleOrderInfo(String batchCode) {
        Map<String, String> param = Maps.newHashMapWithExpectedSize(1);
        param.put("bno", batchCode);
        String mesSaleOrderString = MyHttpClientUtil.sendPostRequest(
                mesConfig.getAddress() + mesConfig.getSaleOrderInfoUrl(),
                mesTokenService.buildTokenHeader(),
                JSONObject.toJSONString(param),
                MyHttpClientUtil::handleJsonResponse
        );
        // 得到mes销售订单中的存货列表
        MesCommonResult<List<MesSaleOrderInfo>> mesSaleOrderResult = JSONObject.parseObject(mesSaleOrderString, new TypeReference<MesCommonResult<List<MesSaleOrderInfo>>>() {
        }.getType());

        if (Objects.nonNull(mesSaleOrderResult) && mesSaleOrderResult.isSuccess()) {
            List<MesSaleOrderInfo> infoList = mesSaleOrderResult.getResult();

            if (Objects.isNull(infoList) || infoList.isEmpty()) {
                log.error("SaleOrderAppService.getMesSaleOrderInfo response body is null : batchCode [{}]", batchCode);
                return Lists.newArrayList();
            }

            List<JSONObject> responseBodyJson = JSONObject.parseObject(JSONObject.toJSONString(infoList), new TypeReference<ArrayList<JSONObject>>(){}.getType());

            List<MesSaleOrderInfo> resList = Lists.newArrayList();
            for (JSONObject info : responseBodyJson) {
                // 有部分记录存在非法空格，所以去掉了前后的空格
                resList.add(JSONObject.parseObject(JSONObject.toJSONString(info).replace("\" ", "\"").replace(" \"", "\""), MesSaleOrderInfo.class));
            }
            return resList;
        }

        return Lists.newArrayList();
    }

    /**
     * 查询U8中的销售订单
     *
     * @param saleOrderQueryParam U8销售订单查询参数对象
     * @return 销售订单对象，没有查到返回null
     */
    public U8SaleOrderQueryResult querySaleOrderFromU8(U8SaleOrderQueryParam saleOrderQueryParam) {
        SaleOrderService saleOrderService = new SaleOrderService();
        JSONObject saleOrderGetResult = null;

        try {
            saleOrderGetResult = saleOrderService.get(saleOrderQueryParam.getId(), yonYouConfig.getToAccount());
        } catch (OpenAPIException e) {
            log.error("SaleOrderAppService isNotExistOnU8 saleOrderService error : {}", e.getMessage());
            // throw new RuntimeException(e);
            return null;
        }

        return JSON.parseObject(JSONObject.toJSONString(saleOrderGetResult), U8SaleOrderQueryResult.class);
    }

    /**
     * 判断订单是否未被录入
     *
     * @param saleOrderQueryParam U8销售订单查询参数对象
     * @return 判断结果
     */
    public boolean isNotExistOnU8(U8SaleOrderQueryParam saleOrderQueryParam) {

        U8SaleOrderQueryResult saleOrderQueryResult = querySaleOrderFromU8(saleOrderQueryParam);

        if (Objects.isNull(saleOrderQueryResult)) {
            log.info("SaleOrderAppService isNotExistOnU8 : [{}] is not exist u8 ", saleOrderQueryParam.getId());
        }
        return Objects.isNull(saleOrderQueryResult);
    }

    /**
     * 向U8中添加销售订单
     *
     * @param u8SaleOrderAddParam 销售订单添加参数
     * @return 是否添加成功
     */
    public U8CommonSyncResponse addSaleOrderToU8(U8SaleOrderAddParam u8SaleOrderAddParam) {

        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("saleorder", u8SaleOrderAddParam);
        SaleOrderService saleOrderService = new SaleOrderService();
        JSONObject addResult = null;
        try {
            addResult = saleOrderService.add(JSONObject.toJSONString(paramMap), yonYouConfig.getToAccount());
        } catch (OpenAPIException e) {
            log.error("SaleOrderAppService addSaleOrderToU8 error 1 : {}", e.getMessage());
            // throw new RuntimeException(e);
            return null;
        }

        return Objects.nonNull(addResult) ? JSONObject.parseObject(JSONObject.toJSONString(addResult), U8CommonSyncResponse.class) : null;
    }
}
